import axios from 'axios';
import qs from 'qs';
import {randomString} from '../lib/function'
import { MessageBox } from 'element-ui';

// export const baseURL='http://vue.uxuew.cn/';
export const baseURL='http://tp.eexueche.com/index.php/jiaxiao/';
var option={
	  baseURL,
	  timeout: 10000,
	  headers: {'Accept': 'application/json'},
	  //responseType:'json'
	  //withCredentials:true,
	  headers: {'X_REQUESTED_WITH': 'xmlhttprequest'}
	}

var token=sessionStorage.getItem('token');
if(!token) {
	token=randomString(16);
	sessionStorage.setItem('token',token);
}
option.headers['token']=token;

var ajax = axios.create(option);

export const request=(url,params,cb,type)=>{
	let config={url:url};
	if(type&&type=='post') {
		config.method=type;
		config.data=qs.stringify(params);
		//config.data=params
	}else{
		config.params=params;
	}
	ajax.request(config).then((res)=>{
		  if(process.env.NODE_ENV !== 'production') console.log(res);
			if(typeof res.data=='string'){
				res.data={type:'warning',title:'数据格式错误',message:res.data};
				}
			else{
				switch(res.data.status){
					case 0:res.data={type:'info',title:'消息',message:res.data.info};break;
					case -1://没有登录
				   	if(sessionStorage.getItem('user')) {
					   MessageBox.confirm('系统会话已过期，请点击确定重新登录', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {
							  sessionStorage.removeItem('user');
							  sessionStorage.removeItem('menu');
							  location.reload();
						  }).catch(()=> {});
			        }
				   res.data={type:'info',title:'消息',message:'会话已过期，请重新登录'};
				   break;
				}
			}
			typeof cb == "function" && cb(res.data);//回调
		}).catch((error)=>{//请求错误
			  cb({type:'error',title:'信息',message:error.message});
			});
}
